var path = require('path');
var fs = require('fs');
var Client = require('ftp');

/*
* opt.host = "127.0.0.1";
* opt.port = 21
* opt.user = ""
* opt.password = ""
*/
var createFtpClient = function (opt, onReady) {
    if (!opt || !opt.host) {
        console.log("createFtpClient error");
        return null;
    }

    var c = new Client();
    var hasReady = false;
    var tick = false;
    c.on('ready', function () {
        hasReady = true;
        if (!tick) {
            console.log("tick ready");
            tick = true;
            onReady(true);
        }
    });
    c.on('error', function (err) {
        hasReady = false;
        if (!tick) {
            console.log("tick error", err);
            tick = true;
            onReady(false);
        }
    });

    c.showList = (path, callback) => {
        if (!hasReady) {
            callback(false);
            return;
        }
        c.list(path, function (err, list) {
            if (err) {
                callback(false);
                return;
            }
            let files = [];
            list.forEach(function (element, index, array) {
                let file = element.name;
                if (element.type === 'd') {
                    file += "/";
                }
                files.push(file);
            });
            callback(files);
        });
    };

    try {
        c.connect(opt);
    } catch (error) {
        console.log(error);
        c.destroy();
        c = null;
    }
    return c;
};

module.exports = createFtpClient;
